<template>
    <div style=" position: relative;"><el-card>
            <template #header>
                <!-- 搜索 -->
                <div>
                    <el-select style="width: 120px;" v-model="find_data.childSys" placeholder="子系统">
                        <el-option label="全部" value=""></el-option>
                        <el-option label="旅行社" value="PC_TRAVEL_AGENCY"></el-option>
                        <el-option label="车队" value="PC_CAR_TEAM"></el-option>
                        <el-option label="酒店" value="PC_HOTEL"></el-option>
                    </el-select>
                    <el-select v-model="find_data.companyNum" placeholder="请选择查询车队" filterable clearable
                        style="width: 220px;margin-left: 20px;">
                        <el-option v-for="(ct, index) in  getCompanyCombo_list " :key="index" :label="ct.company_name"
                            :value="ct.company_num">
                            <span style="float: left">{{ ct.company_name }}</span>
                            <span style="
                            float: right;
                            color: var(--el-text-color-secondary);
                            font-size: 13px;
                          ">{{ ct.company_num }}</span>
                        </el-option>
                    </el-select>

                    <el-button style="margin-left: 20px;height:30px" @click="search_btn" type="primary"
                        icon="Search">搜索</el-button>
                </div>
                <!-- 功能按钮 -->
                <div style="margin-top:10px;">
                    <!-- <el-button @click="add_btn" type="primary" icon="SuccessFilled">添加</el-button> -->
                    <el-button @click="up_btn" type="warning" icon="WarnTriangleFilled">初始化车队菜单</el-button>
                    <!-- <el-button @click="del_btn" type="danger" icon="CircleCloseFilled">删除</el-button> -->
                </div>
            </template>
            <div>
                <!-- @row-click="selection_change_btn" -->
                <el-table highlight-current-row ref="srcMenuListTb" row-key="id" border fit height="67vh" :data="list_data"
                    style="width: 100%" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
                    <!-- <el-table-column type="selection" width="35" /> -->
                    <!-- <el-table-column label="编号" width="55" fixed type="index" /> -->

                    <template v-for="item in table_data_list_new" :key="item.field">
                        <el-table-column v-if="item.off" :width="item.width" :prop="item.field" :label="item.label">

                            <template v-if="item.field == 'menuName'" #="{ row, column, $index }">
                                <span style="font-weight: 700;"> <el-icon>
                                        <component :is="row.micon"></component>
                                    </el-icon> {{ row.menuName }}</span>
                            </template>
                            <template v-if="item.field == 'mname'" #="{ row, column, $index }">
                                <span style="font-weight: 700;"> {{ row.mname }}</span>
                            </template>
                            <template v-if="item.field == 'mtype'" #="{ row, column, $index }">
                                <span
                                    :style="row.mtype == 'SIDEBAR_MENU_GROUP' ? 'color:yellow;' : row.mtype == 'SIDEBAR_MENU'
                                        ? 'color:green;' : row.mtype == 'FILTER' ? 'color:red;' : row.mtype == 'BUTTON' ? 'color:blue;' : 'color:red;'">{{
        row.mtype == 'SIDEBAR_MENU_GROUP' ? '侧边栏菜单组' : row.mtype == 'SIDEBAR_MENU'
        ? '侧边栏菜单' : row.mtype == 'FILTER' ? '筛选条件' : row.mtype == 'BUTTON' ? '按钮' : '无'
    }}</span>
                            </template>


                            <!-- <template v-if="item.field == 'sysType'" #="{ row, column, $index }">
                                <span>电脑端-单位</span>
                            </template> -->
                            <template v-if="item.field == 'ocState'" #="{ row, column, $index }">
                                <span :style="row.ocState == '1' ? 'color:green;' : row.ocState ==
                                    '0' ? 'color:red;' : 'color:red;'">{{ row.ocState == '1' ? '已开启' : row.ocState ==
        '0' ? '已关闭' : '无' }}</span>
                            </template>

                        </el-table-column>
                    </template>
                </el-table>
            </div>

            <!-- <div style="margin-top:20px">
                <el-pagination @current-change="current_change_btn" @size-change="size_change_btn"
                    v-model:current-page="find_data.page.pageNum" v-model:page-size="find_data.page.pageSize"
                    :page-sizes="[20, 50, 100, 200]" :background="true" layout="prev, pager, next, jumper,->,sizes,total,"
                    :total="total" />
            </div> -->
        </el-card>
    </div>

    <!-- 弹窗 -->
    <div>
        <!-- 表格筛选 -->
        <div style="position: absolute;top:75px;z-index: 2;" :style="icon_off ? 'right:0px;' : 'right:110px;'">
            <el-icon @click="icon_btn" :size="20">
                <Setting />
            </el-icon>
            <div v-show="icon_off"
                style=" position: relative;top:-100px;right:140px;width: 130px;height:430px;background:#fff;overflow: hidden;">
                <div class="cols-set" style="background:#fff;width:90%;height:97%;margin:auto;margin-top:10px;">
                    <div>
                        <el-button-group style="display: flex; ">
                            <el-tooltip effect="dark" placement="bottom">
                                <template #content>注意：拖动下面的项，可以改变表格列的顺序，<br />记得点击保存才会永久生效哦！ </template>
                                <el-button style="width:10px" type="primary" icon="WarningFilled"></el-button>
                            </el-tooltip>
                            <el-button title="重置" type="primary" icon="Refresh" @click="resetTableSet"></el-button>
                            <el-button title="保存" type="primary" icon="Check" @click="saveTableSet"></el-button>
                        </el-button-group>
                        <div ref="sortableContainer" class="col-items" style="height:400px; overflow-y: auto; ">
                            <el-checkbox class="drag_it" @change="checkbox_btn" v-for="item in sortedItems"
                                :key="item.field" v-model="item.off" :label="item.label" border>
                            </el-checkbox>
                        </div>

                    </div>
                </div>
            </div>
        </div>


    </div>
</template>

<script setup>
// import {Plus
// } from '@element-plus/icons-vue'
import Sortable from 'sortablejs';
import { ref, reactive, onMounted, computed } from 'vue'
import {
    adupPrivateSet, getPrivateSetList, getCompanyMenuList, getCompanyCombo, getCompanyRole, initCompanyMenu
} from '@/api/rights_management.js'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import CircularJSON from 'circular-json'
import { line2treeData, scopy, tree2lineData } from '@/utils/common.js'
onMounted(async () => {
    let fleet_menu = JSON.parse(localStorage.getItem('fleet_menu'))
    if (fleet_menu) {
        find_data.companyNum = fleet_menu.companyNum
        find_data.childSys = fleet_menu.childSys
    }

    getPrivateSetList({
        find: '车队菜单',
        page: {
            pageNum: 1,
            pageSize: 999,
        },
    }).then(res => {
        if (res.data.list[0]) {
            table_data_list_new.value = JSON.parse(res.data.list[res.data.list.length - 1].dat)
        } else {
            table_data_list_new.value = table_data_list
        }
    })


    Sortable.create(sortableContainer.value, {
        draggable: '.drag_it',
        ghostClass: 'sortable-ghost',
        onEnd: evt => {
            const targetRow = table_data_list_new.value.splice(evt.oldIndex, 1)[0];
            table_data_list_new.value.splice(evt.newIndex, 0, targetRow);

            // 重新赋值给列数组
            // let cols = that.U.scopy(that.fields);
            // let list = cols.filter(it => { return it.show; });
            // that.$emit('saveSet', {dgName: that.dgName, cols: list});
        }
    })
    getCompanyCombo({ companyRole: "", find: "" }).then(res => {
        getCompanyCombo_list.value = res.data
    })
    // getCompanyRole({}).then(res => {

    // })

    await list_api()
})

//#region 表格数据处理
const table_data_list = reactive([
    { label: '车队菜单名称', field: 'menuName', width: 200, off: true },
    { label: '原始菜单名称', field: 'mname', width: 120, off: true },
    { label: '菜单类型', field: 'mtype', width: 120, off: true },
    { label: '序号', field: 'sortNo', width: 60, off: true },
    // { label: '所属系统', field: 'sysType', width: 120, off: true },
    { label: '开关状态', field: 'ocState', width: 120, off: true },
    { label: '添加时间', field: 'addTime', width: 170, off: true },
])

const table_data_list_new = ref([])
const icon_off = ref(false)
// 创建排序容器的引用
const sortableContainer = ref('')

const icon_btn = () => {
    icon_off.value = !icon_off.value
    console.log(sortableContainer.value)

}
const resetTableSet = () => {
    console.log(table_data_list)
    table_data_list_new.value = JSON.parse(JSON.stringify(table_data_list))
    console.log(table_data_list)
    console.log(table_data_list_new.value)
}
const saveTableSet = () => {
    adupPrivateSet({
        dat: JSON.stringify(table_data_list_new.value),
        tbName: '车队菜单',
        tbNum: "fleet_menu",
    }).then(res => {
        if (res.code == 1) {
            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        } else {
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }
    })
    icon_off.value = false
}

const checkbox_btn = (e, c) => {
    for (let i = 0; i < table_data_list_new.value.length; i++) {
        if (table_data_list_new.value[i].label == c.target._value) {
            table_data_list_new.value[i].off == e

        }

    }

}

const sortedItems = computed(() => {
    return [...table_data_list_new.value].sort((a, b) => a.id - b.id);
})
//#endregion

//#region 分页列表
const getCompanyCombo_list = ref([])
const list_data = ref([])
const find_data = reactive({
    page: {
        pageNum: 1,
        pageSize: 20,
    },
    companyNum: '8112010001',
    childSys: ''
})
const total = ref(0)

// 分页器一夜显示多少数据页面
const size_change_btn = () => {
    find_data.page.pageNum = 1
    list_api()
}

// 分页器跳转页面
const current_change_btn = () => {
    list_api()
}
const linelist = ref([])
const list_api = () => {

    getCompanyMenuList(find_data).then(res => {
        let list = res.data
        // for (let i in list) { list[i].checked = false; }
        list_data.value = line2treeData(list, 'pid', 'sortNo');
        linelist.value = tree2lineData(scopy(list_data.value));
        // total.value = res.data.total
        // 取消当前行选中
        srcMenuListTb.value.clearSelection();
        // 取消当前行高亮
        srcMenuListTb.value.setCurrentRow();
        // 保存选中的行数据
        table_list.value = [];
    })
}
//#endregion



//#region 表格选择
const srcMenuListTb = ref('')
const table_list = ref([])
const selection_change_btn = (row, column, event) => {
    let index = table_list.value.findIndex(it => row.id == it.id);
    if (index != -1) {
        // 已选中，则取消当前行的选中和高亮

        // 取消当前行选中
        srcMenuListTb.value.clearSelection();
        // 取消当前行高亮
        srcMenuListTb.value.setCurrentRow();
        // 保存选中的行数据
        table_list.value = [];
    } else {
        // 取消当前行选中
        srcMenuListTb.value.clearSelection();
        // 选中当前行
        srcMenuListTb.value.toggleRowSelection(row, true);
        // 高亮选中
        srcMenuListTb.value.setCurrentRow(row);
        // 保存选中的行数据
        table_list.value = [row];

    }
    console.log(table_list.value)
}
//#endregion
//#region 初始化
const up_btn = () => {
    if (!find_data.companyNum) {
        return ElMessage({
            message: '请选择一个初始化的车队',
            type: 'warning',
        })
    }
    ElMessageBox.confirm(
        '您确定初始化所选择中的车队菜单权限吗？',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
            distinguishCancelAndClose: 'true',

        }
    )
        .then(() => {
            initCompanyMenu({
                companyNum: find_data.companyNum
            }).then(res => {
                if (res.code == 1) {
                    list_api()
                    return ElMessage({
                        message: res.msg,
                        type: 'success',
                    })
                } else {
                    return ElMessage({
                        message: res.msg,
                        type: 'warning',
                    })
                }
            })
        })
        .catch((e) => {
            if (e == 'cancel') {
                ElMessage({
                    type: 'warning',
                    message: '取消删除成功',
                })
            }

        })

}
//#endregion
// /menu-man/src-menu-list@SrcMenuList
// /company/cus/companyCusList
// 提交
const adupSrcMenuFm = ref('')
const ok_btn = () => {

    adupSrcMenuFm.value.validate((valid) => {
        if (!valid) {
            return false;
        } else {
            if (title.value == '添加原始菜单') {
                adupSrcMenu(add_data).then(res => {
                    if (res.code == 1) {
                        list_api()
                        add_off.value = false
                        return ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                    } else {
                        return ElMessage({
                            message: res.msg,
                            type: 'warning',
                        })
                    }
                })
            } else {


                adupSrcMenu(add_data).then(res => {
                    if (res.code == 1) {
                        list_api()
                        add_off.value = false
                        return ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                    } else {
                        return ElMessage({
                            message: res.msg,
                            type: 'warning',
                        })
                    }
                })
            }
        }


    })


}


//#region 删除
const del_btn = () => {
    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }

    ElMessageBox.confirm(
        '<span style="color:#FFB06F;">此操作将会删除所有关联此菜单的单位菜单数据，确认删除吗？<b style="color:red;">【请谨慎操作】</b></span>',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
            distinguishCancelAndClose: 'true',
            dangerouslyUseHTMLString: true,
        }
    )
        .then(() => {
            delSrcMenu({
                id: table_list.value[0].id
            }).then(res => {
                if (res.code == 1) {
                    list_api()
                    return ElMessage({
                        message: res.msg,
                        type: 'success',
                    })
                } else {
                    return ElMessage({
                        message: res.msg,
                        type: 'warning',
                    })
                }
            })
        })
        .catch((e) => {
            if (e == 'cancel') {
                ElMessage({
                    type: 'warning',
                    message: '取消删除成功',
                })
            }

        })

}
//#endregion

//#region 搜索
const search_btn = () => {
    localStorage.setItem('fleet_menu', CircularJSON.stringify(find_data))
    list_api()
}
//#endregion
</script>

<style scoped lang='scss'>
</style>
<style>
.col-items::-webkit-scrollbar {
    width: 5px !important;
}

.col-items>label {
    margin-left: 0px !important;
    margin-top: 5px;
    width: 100%;
}

.el-table .el-table__cell {
    padding: 0px !important;
}
</style>
<style scoped>
:deep(.el-table__body tr.current-row>td) {
    color: #28A458;
    background: rgb(197, 213, 255) !important;
}
</style>
